package com.cloud.common.security.config;

import cn.dev33.satoken.context.SaHolder;
import cn.dev33.satoken.filter.SaServletFilter;
import cn.dev33.satoken.interceptor.SaInterceptor;
import cn.dev33.satoken.router.SaRouter;
import cn.dev33.satoken.same.SaSameUtil;
import cn.dev33.satoken.stp.StpUtil;
import com.cloud.common.core.result.Result;
import com.cloud.common.core.util.JsonUtil;
import jakarta.annotation.Resource;
import org.springframework.boot.autoconfigure.AutoConfiguration;
import org.springframework.context.annotation.Bean;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;


/**
 * 权限安全配置
 */
@AutoConfiguration
public class SecurityConfiguration implements WebMvcConfigurer {

	@Resource
	private  WhiteUrlsProperties whiteUrlsProperties;

	@Override
	public void addInterceptors(InterceptorRegistry registry) {
		registry.addInterceptor(new SaInterceptor(handle -> {
			SaRouter
					.match("/**")
					.notMatch(whiteUrlsProperties.getWhiteUrls())
					.check(r -> StpUtil.checkLogin());
		})).addPathPatterns("/**");
	}


//	@Bean
	public SaServletFilter getSaServletFilter() {
		String[] whiteUrls=whiteUrlsProperties.getWhiteUrls().toArray(new String[whiteUrlsProperties.getWhiteUrls().size()]);
		return new SaServletFilter()
				.addInclude("/**")
				.addExclude(whiteUrls)
				.setAuth(obj -> {
					// 校验 Same-Token 身份凭证
					// 以下两句代码可简化为：SaSameUtil.checkCurrentRequestToken();
					String token = SaHolder.getRequest().getHeader(SaSameUtil.SAME_TOKEN);
					SaSameUtil.checkToken(token);
				})
				.setError(e -> {
					SaHolder.getResponse().setHeader("Content-Type","application/json;charset=utf-8");
					return JsonUtil.toJsonString(Result.error(e.getMessage()));
				});
	}
}
